package Tree;

public class _106_ConstructBinaryTreefromInorderandPostorderTraversal {
    int[] inorder;
    int[] postorder;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.inorder = inorder;
        this.postorder = postorder;
        return addNode(postorder.length - 1, 0, inorder.length - 1);
    }

    public TreeNode addNode(int postEnd, int inStart, int inEnd) {
        if (postEnd < 0 || inStart > inEnd) {
            return null;
        }
        TreeNode newNode = new TreeNode(postorder[postEnd]);
        int inIndex = 0;
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == newNode.val) {
                inIndex = i;
            }
        }
        newNode.right = addNode(postEnd - 1, inIndex + 1, inEnd);
        newNode.left = addNode(postEnd - (inEnd - inIndex) - 1, inStart, inIndex - 1);
        return newNode;
    }
}
